package com.company.www;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HomeWork1 {
	/*	1)	、查看指定URL的HTML源文档内容？
		提示：使用URL类和URLConnection类
		
		String url = “http://hotels.ctrip.com/hotel/shanghai2#ctm_ref=hod_hp_sb_lst”;
	*/
	public static void main(String[] args) {
		String url = "http://hotels.ctrip.com/hotel/shanghai2#ctm_ref=hod_hp_sb_lst";
		try {
			//第一步骤.通过在 URL 上调用 openConnection 方法创建连接对象
			URL url2 = new URL(url);
			URLConnection urlc = url2.openConnection();//url调用openConnection建立与真正对象的连接
			//第二步骤1.1设置访问根据需求设置请求需求
			urlc.setUseCaches(false);
			urlc.setReadTimeout(5000);//设置请求时间相应
			//第二步骤1.2：设置请求属性
			urlc.setRequestProperty("accept", "*/*");
			urlc.setRequestProperty("connection", "keep-Alive");
			
			//第三步骤;通过connect建立与远程对象的连接
			urlc.connect();
			
			//第四步骤：远程对象可以访问，远程对象的头字段和内容变为可访问
			//4.1获取相应的头文字
			Map<String, List<String>> heads = urlc.getHeaderFields();
			System.out.println(heads);
			
			//4.2获取响应的正文
			StringBuffer result = new StringBuffer();
			String tem = null;
			//字节转化字符流
			BufferedReader bf = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
			while ((tem = bf.readLine()) != null) {
				result.append(tem);
			}
			//关闭流资源
			bf.close();
			System.out.println(result);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
